package com.zhilianbao.leyaogo.view.expandview;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;

import com.zhilianbao.leyaogo.R;

/**
 * ClassName: ExpandableView <br>
 * Description: 可展开折叠的View<br>
 * Author: Cyarie <br>
 * Created: 2016/4/12 11:49 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class ExpandableView extends FrameLayout {

    /**
     * 动画是否正在执行
     */
    private boolean isAnimRunning = false;
    /**
     * 是否展开
     */
    private boolean isOpened = false;
    /**
     * 动画持续时间
     */
    private int duration;
    /**
     * 内容视图
     */
    private FrameLayout contentLayout;
    /**
     * 头部视图
     */
    private FrameLayout headerLayout;
    /**
     * 右边箭头
     */
    public ImageView rightImageView;
    /**
     * 动画
     */

    private Animation anim;


    public ExpandableView(Context context) {
        super(context);
    }

    public ExpandableView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ExpandableView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * 初始化
     *
     * @param context 上下文
     * @param attrs   属性
     */
    private void init(final Context context, AttributeSet attrs) {
        final View rootView = View.inflate(context, R.layout.view_expandable, this);
        headerLayout = (FrameLayout) rootView.findViewById(R.id.view_expandable_headerLayout);
        contentLayout = (FrameLayout) rootView.findViewById(R.id.view_expandable_contentLayout);
        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableView);
        final int headerID = typedArray.getResourceId(R.styleable.ExpandableView_ev_headerLayout, -1);
        final int contentID = typedArray.getResourceId(R.styleable.ExpandableView_ev_contentLayout, -1);
        if (headerID == -1 || contentID == -1)
            throw new IllegalArgumentException("HeaderLayout and ContentLayout cannot be null!");
        if (isInEditMode())
            return;
        duration = typedArray.getInt(R.styleable.ExpandableView_ev_duration, 200);
        final View headerView = View.inflate(context, headerID, null);
        headerView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        rightImageView = (ImageView) headerView.findViewById(R.id.common_img_right);
        headerLayout.addView(headerView);
        final View contentView = View.inflate(context, contentID, null);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        contentLayout.addView(contentView);
        contentLayout.setVisibility(GONE);
        typedArray.recycle();
    }

    /**
     * 展开View
     *
     * @param v
     */
    private void expand(final View v) {
        v.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        final int targetHeight = v.getMeasuredHeight();
        v.getLayoutParams().height = 0;
        v.setVisibility(VISIBLE);

        anim = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1)
                    isOpened = true;
                v.getLayoutParams().height = (interpolatedTime == 1) ? LayoutParams.WRAP_CONTENT : (int) (targetHeight * interpolatedTime);
                v.requestLayout();
            }


            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        anim.setDuration(duration);
        v.startAnimation(anim);
    }

    /**
     * 折叠View
     *
     * @param v
     */
    private void collapse(final View v) {
        final int initialHeight = v.getMeasuredHeight();
        anim = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1) {
                    v.setVisibility(View.GONE);
                    isOpened = false;
                } else {
                    v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                    v.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        anim.setDuration(duration);
        v.startAnimation(anim);
    }

    /**
     * 是否展开
     *
     * @return
     */
    public Boolean isOpened() {
        return isOpened;
    }


    /**
     * 获得头部视图
     *
     * @return
     */
    public FrameLayout getHeaderLayout() {
        return headerLayout;
    }

    /**
     * 获得内容视图
     *
     * @return
     */
    public FrameLayout getContentLayout() {
        return contentLayout;
    }

    /**
     * 隐藏Content 显示动画
     */
    public void hide() {

        hide(true);
    }

    /**
     * 显示Content 显示动画
     */
    public void show() {

        show(true);
    }

    /**
     * 设置展开图标
     */
    public void setFold() {
        if (rightImageView != null) {
            rightImageView.setImageResource(R.drawable.ic_fold);
        }
    }

    /**
     * 设置收缩图标
     */
    public void setUnFold() {
        if (rightImageView != null) {
            rightImageView.setImageResource(R.drawable.ic_unfold);
        }
    }


    /**
     * 显示内容
     *
     * @param isAnim 是否动画
     */
    public void show(boolean isAnim) {
        setFold();
        if (isAnim) {
            if (!isAnimRunning) {
                expand(contentLayout);
                isAnimRunning = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isAnimRunning = false;
                    }
                }, duration);
            }
        } else {
            this.isOpened = true;
            contentLayout.setVisibility(VISIBLE);
            contentLayout.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
            contentLayout.invalidate();
        }
    }


    /**
     * 隐藏内容 是否动画
     *
     * @param isAnim
     */
    public void hide(boolean isAnim) {
        setUnFold();
        if (isAnim) {
            if (!isAnimRunning) {
                collapse(contentLayout);
                isAnimRunning = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isAnimRunning = false;
                    }
                }, duration);
            }
        } else {
            isOpened = false;
            contentLayout.getLayoutParams().height = 0;
            contentLayout.invalidate();
            contentLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
        anim.setAnimationListener(animationListener);
    }

    public boolean isAnimRunning() {
        return isAnimRunning;
    }

    /**
     * 隐藏所有其他打开的Item
     *
     * @param listView
     * @param pos
     */
    public void hideOtherOpenItem(ListView listView, int pos) {
        if (listView == null)
            throw new IllegalArgumentException("ListView must not be null");
        if (listView.getAdapter() == null)
            throw new IllegalArgumentException("ListView's adapter must not be null");
        for (int i = 0; i < listView.getAdapter().getCount(); i++) {
            if (i != pos) {
                if (listView.getChildAt(i) instanceof ExpandableView && ((ExpandableView) listView.getChildAt(i)).isOpened()) {
                    ((ExpandableView) listView.getChildAt(i)).hide();
                    //                    ((Item) listView.getAdapter().getItem(i)).setOpenIndicator(false);
                }
            }
        }
    }
}
